<template>
  <el-dialog
    v-model="isShowAddDialog"
    width="720"
    :align-center="true"
    :show-close="false"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <template #header>
      <title-view title="新建客户"></title-view>
    </template>
    <el-form ref="ruleDialogFormRef" :model="addClientForm" :rules="addClientFormRules" label-width="100px" status-icon>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input v-model.trim="addClientForm.customerName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="电话" prop="mobileCode">
        <el-input v-model.number="addClientForm.mobileCode" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="备用电话1">
        <el-input v-model.number="addClientForm.mobileCode1" :maxlength="11" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="备用电话2">
        <el-input v-model.number="addClientForm.mobileCode2" :maxlength="11" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="装修区域" prop="fitmentAreaIds">
        <el-cascader
          ref="cascaderRef"
          :props="{
            label: 'name',
            value: 'cityCode'
          }"
          v-model="addClientForm.fitmentAreaIds"
          @change="handelChangeFitmentArea"
          :options="addressData"
          clearable
        />
      </el-form-item>
      <el-form-item label="小区名称" prop="residence">
        <el-input
          v-model.trim="addClientForm.residence"
          :autosize="{ minRows: 1 }"
          type="textarea"
          placeholder="小区名称"
          @clear="handelClearCommunityName"
          @change="handelChangeCommunityName"
        />
      </el-form-item>
      <el-form-item label="楼栋号" prop="buildingName">
        <el-input v-model="addClientForm.buildingName" placeholder="楼栋号" @change="handelChangeBuildingName" />
      </el-form-item>
      <el-form-item label="项目地址" prop="address">
        <el-input v-model="addClientForm.address" :autosize="{ minRows: 1 }" readonly type="textarea" placeholder="项目地址" />
      </el-form-item>
      <el-form-item label="房屋面积" prop="area">
        <el-input type="number" v-model.number="addClientForm.area" :min="0" />
      </el-form-item>
      <el-form-item label="房屋总价等级">
        <el-select v-model="addClientForm.totalPriceLevel" @change="changeTotalPriceLevel">
          <el-option v-for="item in totalPriceLevels" :key="item.dictCode" :label="item.dictLabel" :value="item.dictCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源">
        <el-select v-model="addClientForm.fromType" @change="changeFromType">
          <el-option v-for="item in source_classification" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="细分渠道">
        <el-select v-model="addClientForm.fromDetailType" @change="changeFromDetailType">
          <el-option v-for="item in fromDetails" :key="item.dictCode" :label="item.dictLabel" :value="item.dictCode"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房屋类型">
        <el-select v-model="addClientForm.houseType" @change="changeHouseType">
          <el-option v-for="item in crm_house_types" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="装修用途">
        <el-checkbox-group v-model="addClientForm.fitment" @change="changeFitment">
          <el-checkbox v-for="item in crm_fitments" :key="item.value" :value="item.value">{{ item.label }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="装修类型">
        <el-select v-model="addClientForm.businessType" @change="changeBusinessType">
          <el-option v-for="item in crm_business_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户预算">
        <el-select v-model="addClientForm.budget" @change="changeBudget">
          <el-option
            v-for="item in customerBudgets"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否期房">
        <el-radio-group v-model="addClientForm.isFutures">
          <el-radio value="1" size="large">是</el-radio>
          <el-radio value="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="addClientForm.remark"
          :autosize="{ minRows: 4 }"
          :maxlength="200"
          show-word-limit
          type="textarea"
          placeholder="备注"
        />
      </el-form-item>
      <el-form-item label="业务人员" prop="businessUserId">
        <!--     TODO：下拉搜索框   -->
        <el-select
          popper-class="select-user-popper"
          v-model="addClientForm.businessUserId"
          placeholder="请选择"
          @change="changeUser"
        >
          <template #header>
            <div class="content-item-search">
              <el-input placeholder="请输入关键词" v-model="searchUserkeyword" @change="handelSearchUser" />
              <svg-icon iconClass="searchBox-icon" style="font-size: 24px" @click="handelSearchUser" />
            </div>
          </template>
          <el-option
            v-for="userItem in selectUserList"
            :key="userItem.userId"
            :v-loading="isSelectUserListLoading"
            :label="userItem.userName"
            :value="userItem.userId"
          >
            <template #default>
              <div class="content-item-option">
                <span>{{ userItem.deptName }}</span>
                <span>{{ userItem.userName }}</span>
              </div>
            </template>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务部门" prop="deptId">
        <el-select v-model="addClientForm.deptId">
          <el-option v-for="item in depts" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="portaintId">
        <el-select v-model="addClientForm.portaintId" @change="changeProfile">
          <el-option v-for="item in customerProfile" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button style="width: 92px; background-color: #f2f3f5" @click="handelCancel">取消</el-button>
        <el-button style="width: 92px" type="primary" @click="handelSubmit" :loading="isSubmitLoading">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="visibleAddSure" width="400" center align-center :show-close="false">
    <div class="sure">
      <div>
        <el-icon>
          <Warning />
        </el-icon>
      </div>
      <span>{{ addSureText }}</span>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeAdd">取 消</el-button>
        <el-button type="primary" @click="handelSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, getCurrentInstance, nextTick } from "vue";
import { Warning } from "@element-plus/icons-vue";
import { dictList, getBudget, allPortraitList } from "@/apis/dict/dict";
import { addClientInfo, checkRepeat } from "@/apis/clientManager";
import { userDeptByUserId, departmentTree, userBusinessByDeptId, userRoleList, searchBusinessUser } from "@/apis/user";
import useAddressByKeyword from "@/hooks/AMap/useAddressByKeyword";
import { addClientFormInit, addClientFormRules } from "@/views/client/utils/config";
import defaultConfig from "@/settings";
import addressData from "@/assets/pca-code";
import useUserStore from "@/store/modules/user";
import { ElMessageBox } from "element-plus";

const addSureText = ref("");
const visibleAddSure = ref(false);
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:modelValue", "submit"]);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});
const userStore = useUserStore();

const isShowAddDialog = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

//运营平台字典—— 业务类型、房屋类型、装修用途、客户来源
const { crm_business_type, crm_house_types, crm_fitments, source_classification } = proxy.$dict(
  defaultConfig.dicts.crm_business_type,
  defaultConfig.dicts.crm_house_types,
  defaultConfig.dicts.crm_fitments,
  defaultConfig.dicts.source_classification
);
// saas租户自定义字典——房屋总价等级
const getDictData = async () => {
  const { data } = await dictList({ dictType: defaultConfig.dicts.HOUSE_PRICE_TYPE });
  totalPriceLevels.value = data || [];
  console.log(data, "<<<房屋总价等级");
};
/**
 * 根据业务类型查询客户预算
 * 根据客户来源查询细分渠道
 */
const customerBudgets = ref([]);
const fromDetails = ref([]);
const getCustomerSource = async () => {
  const postData = {
    dictType: defaultConfig.dicts.COSTEM_PREPRICE,
    dictLabel: addClientForm.value.businessTypeName
  };
  const { data } = await getBudget(postData);
  customerBudgets.value = data || [];
};
const getFromDetailTypes = async () => {
  const postData = {
    dictType: defaultConfig.dicts.COSTEM_ORIGIN,
    dictLabel: addClientForm.value.fromTypeName
  };
  const { data } = await getBudget(postData);
  fromDetails.value = data || [];
};
// 部门树
const defaultTreeProps = {
  children: "children",
  label: "deptName"
};
const deptTreeData = ref([]);
const deptUserList = ref([]);
const deptUserId = ref("");
const handleNodeClick = data => {
  deptUserId.value = data.deptId;
  const params = {
    deptId: data.deptId
  };
  getUserListByRole(params);
};
const getDeptTree = async () => {
  const { data } = await departmentTree();
  deptTreeData.value = data;
};
const getUserListByRole = async params => {
  const { data } = await userBusinessByDeptId(params);
  deptUserList.value = data;
};

// 区域
const addressCity = ref("");
const handelAreaInfo = () => {
  const nodeLabel = proxy.$refs.cascaderRef.getCheckedNodes();
  if (nodeLabel?.length) {
    const [province, city, county] = nodeLabel[0].pathLabels;
    addressCity.value = ["县", "市辖区"].includes(city) ? `${province}${county}` : `${province}${city}${county}`;
  }
};
const handelChangeFitmentArea = () => {
  handelAreaInfo();
  // addClientForm.value.residence = "";
  addClientForm.value.address = `${addressCity.value}${addClientForm.value.residence}${addClientForm.value.buildingName}`;
};

// 小区名称
const handelChangeCommunityName = () => {
  addClientForm.value.address = `${addressCity.value}${addClientForm.value.residence}${addClientForm.value.buildingName}`;
};
const handelClearCommunityName = () => {
  addClientForm.value.fitmentAreaIds = [];
  addClientForm.value.residence = "";
  addClientForm.value.address = `${addressCity.value}${addClientForm.value.residence}${addClientForm.value.buildingName}`;
};
// const handelChangeResidence = () => {
//   addClientForm.value.address = `${addressCity.value}${addClientForm.value.residence}${addClientForm.value.buildingName}`;
// };
// 楼栋号
const handelChangeBuildingName = () => {
  addClientForm.value.address = `${addressCity.value}${addClientForm.value.residence}${addClientForm.value.buildingName}`;
};
//  房屋总价等级
const totalPriceLevels = ref([]);
const changeTotalPriceLevel = data => {
  const totalPriceLevel = totalPriceLevels.value.find(item => item.dictCode === data);
  addClientForm.value.totalPriceLevelName = totalPriceLevel?.dictLabel ?? "";
};
// 客户来源
const changeFromType = data => {
  const fromType = source_classification.value.find(item => item.value === data);
  addClientForm.value.fromTypeName = fromType?.label ?? "";
  addClientForm.value.fromDetailType = "";
  addClientForm.value.fromDetailTypeName = "";
  getFromDetailTypes();
};
// 细分渠道
const changeFromDetailType = data => {
  const fromDetail = fromDetails.value.find(item => item.dictCode === data);
  addClientForm.value.fromDetailTypeName = fromDetail.dictLabel;
};
// 房屋类型
const changeHouseType = data => {
  const houseType = crm_house_types.value.find(item => item.value === data);
  addClientForm.value.houseTypeName = houseType?.label ?? "";
};
// 装修用途
const changeFitment = data => {
  const fitmentName = data.reduce((pre, cur) => {
    const fitments = crm_fitments.value.find(subItem => subItem.value === cur);
    pre.push(fitments.label);
    return pre;
  }, []);
  addClientForm.value.fitmentName = fitmentName?.join(",") || "";
};
// 业务类型
const changeBusinessType = data => {
  const houseType = crm_business_type.value.find(item => item.value === data);
  addClientForm.value.businessTypeName = houseType?.label ?? "";
  addClientForm.value.budgetName = "";
  addClientForm.value.budget = "";
  getCustomerSource();
};
// 客户预算
const changeBudget = data => {
  const budget = customerBudgets.value.find(item => item.dictCode === data);
  addClientForm.value.budgetName = budget.dictLabel;
};
// 业务类型（原客户画像）
const customerProfile = ref([]);
const getPortraitList = async () => {
  const { data } = await allPortraitList();
  if (data?.length) {
    customerProfile.value = data.map(item => {
      return {
        label: item.portraitName,
        value: item.portraitId
      };
    });
  }
};
const changeProfile = data => {
  const profile = customerProfile.value.find(item => item.value === data);
  addClientForm.value.portaintName = profile?.label ?? "";
};
// 业务人员
const changeUserClick = data => {
  getUserDeptList(data.userId);
  addClientForm.value.businessUserId = data.userId;
  addClientForm.value.businessUserName = data.nickName;
};
// 业务部门
const depts = ref([]);
const getUserDeptList = async userId => {
  const { data } = await userDeptByUserId(userId);
  deptUserId.value && (addClientForm.value.deptId = deptUserId.value);
  if (data?.length) {
    depts.value = data.map(item => {
      return {
        label: item.deptName,
        value: item.deptId
      };
    });
  }
};
const handelChangePersonnel = () => {
  console.log("业务人员");
};

// 根据所选省市区搜索地址
const addressList = ref([]);
const isLoadingSearch = ref(false);
const getAddress = async keyWord => {
  try {
    if (!keyWord) {
      return (addressList.value.length = 0);
    }
    isLoadingSearch.value = true;
    const autoOptions = {
      city: addressCity.value,
      citylimit: true,
      pageSize: 1000,
      extensions: "base"
    };
    addressList.value = await useAddressByKeyword(autoOptions, `${addressCity.value}${keyWord}`);
    isLoadingSearch.value = false;
  } catch (err) {
    isLoadingSearch.value = false;
  }
};
const handelSearchAddress = proxy.$lodash.debounce(getAddress, 1000);

/**
 * 下拉搜索业务员
 */
const isSelectUserListLoading = ref(false);
const searchUserkeyword = ref("");
const selectUserList = ref([]);
const getBusinessUserList = async () => {
  if (!searchUserkeyword.value) return;
  isSelectUserListLoading.value = true;
  const { data } = await searchBusinessUser({
    userName: searchUserkeyword.value
  });
  selectUserList.value = data ?? [];
  isSelectUserListLoading.value = false;
};
const handelSearchUser = proxy.$lodash.debounce(getBusinessUserList, 1000);
const changeUser = e => {
  const user = selectUserList.value.find(item => item.userId === e);
  addClientForm.value.businessUserName = user?.userName;
  addClientForm.value.deptId = user?.deptId;
  getUserDeptList(e);
};

/**
 * 提交
 */
const addClientForm = ref({ ...addClientFormInit });
const isSubmitLoading = ref(false);
const getBusinessRole = async () => {
  const { data } = await userRoleList(userStore.userInfo.userId);
  const roles = data ?? [];
  const result = roles.some(item => item.isBusiness);
  if (result) {
    addClientForm.value.businessUserId = userStore.userInfo.userId;
    addClientForm.value.businessUserName = userStore.userInfo.nickName;
    addClientForm.value.deptId = userStore.userInfo.mainDeptId;
    selectUserList.value = [
      {
        userId: userStore.userInfo.userId,
        userName: userStore.userInfo.nickName,
        deptId: userStore.userInfo.mainDeptId,
        deptName: userStore.userInfo.mainDeptName
      }
    ];
    getUserDeptList(userStore.userInfo.userId);
  }
};

const closeAdd = () => {
  visibleAddSure.value = false;
  isRepeateName.value = false;
};
const isRepeatePhone = ref(false); //电话是否重复 false 否 true 是
const isRepeateName = ref(false);
const handelSubmit = () => {
  proxy.$refs.ruleDialogFormRef.validate(async val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    if (!isRepeateName.value) {
      repeateName();
      return;
    }
    const postData = {
      ...addClientForm.value,
      isFuturesName: addClientForm.value.isFutures === "1" ? "是" : "否",
      fitment: addClientForm.value.fitment?.join(",") || "",
      fitmentAreaIds: addClientForm.value.fitmentAreaIds?.join(",") || "",
      isVerified: isRepeatePhone.value
    };
    addClientInfo(postData)
      .then(res => {
        if (res.code == 200) {
          const mobileCodeMsg = res.data?.mobileCode ?? "";
          if (mobileCodeMsg) {
            //重复号码
            submitRepeatPhone(mobileCodeMsg);
            isRepeateName.value = true;
          } else {
            isSubmitLoading.value = false;
            proxy.$modal.msgSuccess("新增成功");
            handelCancel();
            emit("submit");
          }
        }
        isSubmitLoading.value = true;
        visibleAddSure.value = false;
      })
      .catch(() => {
        isSubmitLoading.value = false;
      });
  });
};
/**
 * 重复名称
 */
const repeateName = async () => {
  const res = await checkRepeat(addClientForm.value.customerName);
  isRepeateName.value = true;
  if (!res.data) {
    addSureText.value = res.msg;
    visibleAddSure.value = true;
  } else {
    handelSubmit();
  }
};
//重复号码提交
const submitRepeatPhone = msg => {
  ElMessageBox.confirm(msg, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      isSubmitLoading.value = false;
      isRepeatePhone.value = true;
      handelSubmit();
    })
    .catch(() => {
      isSubmitLoading.value = false;
      isRepeateName.value = false;
    });
};
const handelCancel = () => {
  resetForm();
  isShowAddDialog.value = false;
};
const resetForm = async () => {
  await nextTick();
  proxy.$refs.ruleDialogFormRef.resetFields();
  addressCity.value = "";
  deptUserId.value = "";
  addClientForm.value = { ...addClientFormInit };
};

const initData = async () => {
  getBusinessRole();
  getPortraitList();
  // getDeptTree();
  getDictData();
};
initData();
</script>

<style scoped lang="scss">
@use "AddClient";
</style>
<style lang="scss">
@use "@/assets/styles/mixin";

.stage-intention-popper {
  @include mixin.scrollbar;
  max-height: 810px !important;
  overflow-y: auto;

  .el-popper__arrow {
    top: 23px !important;
  }
}

.el-popper.el-popover {
  padding: 0 !important;
}

// 自定义远程搜素
.select-user-popper {
  border: 1px solid #0052d9 !important;
  box-shadow: 0 0 0 2px #d9e1ff !important;
  border-radius: 3px;

  .el-select-dropdown__header {
    padding: 10px 5px 4px 5px !important;
  }

  .el-scrollbar__view > .el-select-dropdown__item {
    @include mixin.flex-align;
    padding-left: 10px;
    padding-right: 10px;
    color: #3d3d3d;
    line-height: 22px;
  }

  .el-popper__arrow::before {
    display: none;
  }
}
</style>
